var aldstat = require("./third/ald-stat.js");
const $ = require('./utils/utils.js')
const errorCode = require('./utils/errorCode.js')
const config = require('./config')
const user = require('./manager/userManager')
const update = require('./manager/updateManager')

const queryUserDepositAmount = require('./config').queryUserDepositAmount;
const getGridList = require('./config').getGridList;
var hostUrl = require('./config').hostUrl;
const actiHostUrl = require('./config').actiHostUrl;
const appversion = require('./config').appversion;
const appid = require('./config').appId;

const loginPage = config.page.login; //登录
const indexPage = config.page.index; //首页
const payPage = config.page.pay; //充值
const gridPage = config.page.gridChoose; //选格子页面
const opendoorPage = config.page.borrowing;
const grabCard = config.page.grabCard;
const unlock = config.unlock;
const opendoor = config.page.borrowing; //开门等待

var app = getApp();

//app.js
App({
    host_url: hostUrl,
    actiHost_url: actiHostUrl,
    appId: appid,

    globalData: {
        userInfo: null,
        appversion: appversion,
        bookShelfId: "",
    },


    /********** life cycle ******************/
    onLaunch: function (res) {
        let that = this
        console.log(`#app_onLaunch()${JSON.stringify(res)} 版本 ${config.appversion}`)
        wx.removeStorageSync("comeFromWXScan")

        // 检查更新        
        update.updateCheck()

        if (res.scene == 1011) {
            //扫码进入
            this.directToChooseGridPage(res)
        }
        if (res.scene = 1044) {
            console.log("#App_onshow_shareTicket", res.shareTicket)
            wx.setStorageSync("shareTicket", res.shareTicket)
        }


        user.checkWXSession().then(data => {
            that.setLoginChange(wx.getStorageSync("isLogin"))
            that.setUserTokenChange(wx.getStorageSync("isLogin"))
            console.log("#app()_onLaunch_已拿到Token", data)
        }).catch(error => {
            that.setUserTokenChange(wx.getStorageSync("isLogin"))
            console.log("#app()_onLaunch_未拿到code", error)
        })
    },

    callUserCheck: function () {
        let that = this
        console.log('#app_callUserCheck()')
        return new Promise((resolve, reject) => {
            user.checkWXSession().then(data => {
                that.setLoginChange(wx.getStorageSync("isLogin"))
                that.setUserTokenChange(wx.getStorageSync("isLogin"))
                console.log("#app()_onLaunch_已拿到Token", data)
                resolve(data)
            }).catch(error => {
                that.setUserTokenChange(wx.getStorageSync("isLogin"))
                console.log("#app()_onLaunch_未拿到code", error)
                reject(error)
            })
        })
    },

    onShow: function (res) {
        // 标识符，为了在进入APP时 告知index  让其进行定位到最近书柜
        wx.setStorageSync("isReLaunch", true)
        console.log("# app_onShow:" + JSON.stringify(res));
        console.log('# app_version: ' + this.globalData.appversion);
        
        // 将app 传入util
        $.getAppInstance(this)

        var that = this;
        this.remainseconds()

        if (res.scene == 1044) {
            console.log("#App_onshow_shareTicket", res.shareTicket)
            wx.setStorageSync("shareTicket", res.shareTicket)
        }

        if (res.query.q) {
            var src = decodeURIComponent(res.query.q);
            var visitorId = that.getQueryStringArgs(src);
            console.log('visitorId:' + visitorId.visitorId);
            if (visitorId.visitorId) {
                wx.setStorageSync('visitorId', visitorId.visitorId);
            } else {
                if (wx.getStorageSync('visitorId')) wx.removeStorageSync('visitorId');
            }
        } else {
            if (wx.getStorageSync('visitorId')) wx.removeStorageSync('visitorId');
        }
    },


    onHide: function () {
        console.log('# app_onHide');
    },


    /*************** Methods **********/

    // 监听 事件
    addListener: function (callback) {
        this.callback = callback;
    },

    setLoginChange: function (data) {
        this.data = data;
        if (this.callback != null) {
            this.callback(data);
        }
    },

    setUserTokenChange: function (data) {
        this.data = data;
        if (this.callback != null) {
            this.callback(data);
        }
    },



    /************* 开柜相关 *************/

    /**************
     *   开柜流程
     * 
     *  扫码方法 -> 判断登陆信息，余额信息-> 获取心愿单信息 -> 获取书格列表 -> 
     * 
     * 
     * 
     * ***********/

    // 直接进入选柜门页面
    directToChooseGridPage: function (res, callBack) {
        console.log(`#app_directToChooseGridPage() ${res.query.q}`);
        wx.setStorageSync("comeFromWXScan", true)
        let that = this
        if (res.query.q) {
            var src = decodeURIComponent(res.query.q);
            var bookcaseId = that.getQueryStringArgs(src);
            if (bookcaseId.bookcaseId) {
                that.globalData.bookShelfId = bookcaseId.bookcaseId
            }

            if (bookcaseId.bookcaseId && wx.getStorageSync("borrowed_count") > 0) {
                if (!wx.getStorageSync('isLogin')) {
                    return;
                }
                that.queryUserDepositAmount(bookcaseId.bookcaseId)
            }
        }
    },


    scanCode: function () {
        console.log(`#app_scanCode()`)
        var that = this;
        //如果未登录，点击扫码先登录
        if (!wx.getStorageSync("isLogin")) {
            let path = config.page.login + "?path=scanCode"
            $.goto(path)
            return;
        }

        that.queryUserDepositAmount();
    },

    //请求余额
    queryUserDepositAmount: function (bookcaseId) {
        console.log(`#app_queryUserDepositAmount()`)
        var that = this;
        //参数res

        let data = {
            usertoken: wx.getStorageSync('usertoken'),
            userid: wx.getStorageSync('userid'),
            isbn: wx.getStorageSync("bookDetail_isbn")
        }

        let url = $.getUrl(queryUserDepositAmount, data)
        $.get(url)
            .then(data => {
                if (data.code != 0) {
                    wx.showModal({
                        content: data.message,
                        confirmColor: "#FF3B30"
                    });
                } else {
                    // 验证押金逻辑
                    if (wx.getStorageSync("scanIsFromLogin") || wx.getStorageSync("scanIsFromWishList")) {
                        setTimeout(function () {
                            that.verifyUserCashAccount(data.detail, function () {

                                if (bookcaseId) {
                                    that.handleShelfCode(bookcaseId, false)
                                } else {
                                    that.toWxScanPage()
                                }
                            })
                        }, 500)

                        return

                    }

                    that.verifyUserCashAccount(data.detail, function () {

                        if (bookcaseId) {
                            that.handleShelfCode(bookcaseId, false)
                        } else {
                            that.toWxScanPage()
                        }

                    })
                };
            })

            .catch(error => {
                let path = config.page.login + "?path=scanCode"
                $.goto(path)
            })

    },

    // 验证用户钱包账户信息
    verifyUserCashAccount: function (info, success) {
        console.log(`#app_verifyUserCashAccount()`, info, wx.getStorageSync("comeFromWXScan"))
        let that = this

        let payUrl = config.page.pay + "?path=index"
        let payDepositUrl = config.page.walletDeposit + "?path=index"
        //押金未充值，跳转充值界面        

        if (info.depositStatus === 0) {
            if (wx.getStorageSync("comeFromWXScan")) {
                wx.setStorageSync("comeFromWXScan", false)
                return
            }

            if (wx.getStorageSync("scanIsFromLogin")) {
                wx.removeStorageSync("scanIsFromLogin")
                $.goto(payDepositUrl)
                return
            }

            //弹框确认跳转充值页面
            wx.showModal({
                content: "您还未交付押金,马上开启智慧之旅",
                confirmText: "充值",
                cancelText: "返回",
                success: function (res) {
                    //点击确定进入充值页面
                    if (res.confirm) {
                        $.goto(payDepositUrl)
                    } else {
                        wx.hideLoading()
                    }
                }
            });
        } else if (info.cashStatus === 0) {
            //有押金，判断是否有余额，余额不足，跳转充值界面
            if (wx.getStorageSync("comeFromWXScan")) {
                wx.setStorageSync("comeFromWXScan", false)
                return
            }
            wx.showModal({
                content: "您的余额不足，读了很多绘本哦！去充值加油~",
                confirmText: "充值",
                cancelText: "返回",
                success: function (res) {
                    if (res.confirm) {
                        $.goto(payUrl)
                    } else {
                        wx.hideLoading()
                    }
                }
            });
        } else {
            $.showLoading("正在加载中")
            // 满足条件
            success()

        }
    },

    // 跳转到扫码页面
    toWxScanPage: function () {
        console.log(`#app_toWxScanPage()`)
        var that = this
        wx.setStorageSync('isBeginScanCode', true)
        wx.hideLoading()
        wx.scanCode({
            success: function (res) {
                console.log(`#app_toWxScanPage()_wxScanCode`)
                let qrcode = res.result
                let qrCodeParam = that.getQueryStringArgs(qrcode)

                //扫码成功，返回当前页不再展示扫码
                console.log('扫码:' + JSON.stringify(res));

                let shelf_code = qrCodeParam.bookcaseId;

                if (!shelf_code) {
                    $.hideLoading()
                    wx.showModal({
                        content: '所扫二维码不对，重新扫码？',
                        success: function (res) {
                            if (res.confirm) {
                                that.toWxScanPage();
                            } else if (res.cancel) {
                                $.goto(config.page.index, true)
                            }
                        }
                    })
                    return;
                }

                if (shelf_code) {
                    that.handleShelfCode(shelf_code)
                }

            },
            fail: function (res) {

                //取消扫码，跳转至首页
                console.log(`#app_toWxScanPage()_扫码取消或者失败`)
                wx.removeStorageSync("bookDetail_isbn")
                wx.setStorageSync('scanFlag', 0);
                if (wx.getStorageInfoSync("scanIsFromBorrowList")) {
                    wx.setStorageSync("scanIsFromBorrowList", false)
                    return;
                }

                $.goto(config.page.index, true)
            }
        });

    },

    // 得到shelf_code进行下一步操作
    handleShelfCode: function (shelf_code, showErrorMsg = true) {
        let that = this
        wx.showLoading({
            title: '正在加载中',
        })
        console.log(`#app_handleShelfCode()${shelf_code}`);
        let data = {
            usertoken: wx.getStorageSync('usertoken'),
            userid: wx.getStorageSync('userid'),
            bookcaseId: shelf_code,
            grid_code: wx.getStorageSync("wish_list_grid"),
            isbn: wx.getStorageSync("bookDetail_isbn")
        }
        let url = $.getUrl(queryUserDepositAmount, data)
        $.get(url).then(data => {
            if (data.code != 0) {
                if (showErrorMsg) {
                    wx.showModal({
                        content: data.message,
                        confirmColor: "#FF3B30"
                    });
                }
            } else {
                // 判断是不是直接开柜失败
                if (data.detail.type) {
                    // type == 1  书籍详情 ，type==2 心愿单
                    wx.setStorageSync("openErroType", data.detail.type)
                    wx.setStorageSync("openErrorMsg", data.detail.tip)
                    data.detail.type == 1 ? wx.removeStorageSync("bookDetail_isbn") : wx.removeStorageSync("wish_list_grid")
                }

                that.getClearBookshelfCode(data.detail.shelf_code)
                if (data.detail.grid_code) {
                    wx.setStorageSync("grid_code", data.detail.grid_code)
                    let path = wx.getStorageSync("bookDetail_isbn") > 0 ? "bookDetail" : "wishList"

                    that.openTheDoor(data.detail.grid_code, path)
                } else {
                    that.getWishList(data.detail.shelf_code);
                }
            };
        })
    },

    getClearBookshelfCode: function (shelfCode, success) {

        wx.setStorageSync('bookShelfCode', shelfCode);

        let postData = {
            bookshelf_code: shelfCode
        }
        let url = $.getUrl(config.getShelfInfo, postData);
        $.get(url).then(data => {
            console.log("#app_getClearBookshelfCode()", data)
            if (data.code == errorCode.QRCODE_ANALYSIS_IS_WRONG) {
                if (success) {
                    success(false)
                }
            } else {
                wx.setStorageSync("area", data.detail.area)
                if (success) {
                    success(true, data.detail)
                }

            }

        })
    },


    //二维码规范解析
    getQueryStringArgs: function (url) {
        let args = $.analysisQRCode(url)
        return args;
    },

    // 获取心愿单
    getWishList: function (code) {

        let params = {
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken'),
            shelf_code: code,
            pagesize: 100,
            pageno: 1,
            oper: 0
        }
        let url = $.getUrl(config.queryWishListV1, params)
        $.get(url).then(data => {
            console.log("#app_getWishList()", data)
            if (data.result == 1) {
                var items = data.items.map(item => {
                    return item.isbn
                });
                wx.setStorage({
                    key: 'wish_detail',
                    data: data.items,
                });
                // this.gridList(code, isbn_list);
                wx.setStorageSync("isbn_list", items)
                let gridpage = config.page.gridChoose + "?shelfCode=" + code;
                $.goto(gridpage)
            }
        }).catch(error => {
            console.log(res.data.message);
        })
    },

    // 获取书格列表
    gridList: function (shelf_code, isbn_list) {
        console.log(`#app_gridList${shelf_code, isbn_list}`)
        // $.showLoading()
        //请求当前二维码所在柜子的格子信息
        let data = {
            usertoken: wx.getStorageSync('usertoken'),
            userid: wx.getStorageSync('userid'),
            shelf_code: shelf_code, //,
            isbn_list: isbn_list
        }

        let url = $.getUrl(getGridList, data)
        $.get(url).then(data => {
            if (data.result == 1) {
                let array = Array.from(data.items)
                let newGridItems = array.map(item => {
                    var gridIndex = item.bookgrid_code.substring(11);
                    item.gridIndex = gridIndex;
                    return item
                })

                wx.setStorageSync('gridItems', newGridItems);
                $.goto(config.page.gridChoose)
            } else {
                wx.showModal({
                    content: data.message,
                });
            }
        })
    },

    // 开门
    openTheDoor: function (grid_code, path) {
        wx.removeStorageSync("bookDetail_isbn")
        wx.removeStorageSync("wish_list_grid")
        console.log(`#app_openTheDoor()${grid_code, path}`)
        wx.showLoading({
            title: "正在发送指令...",
            mask: true,
        });

        let params = {
            grid_code: grid_code,
            usertoken: wx.getStorageSync('usertoken'),
            userid: wx.getStorageSync('userid'),
        }

        $.post(config.unlock, params).then(data => {
            wx.hideLoading();
            console.log(data);
            console.log(data.code);
            if (data.code == 0) {
                wx.reLaunch({
                    url: opendoor + "?path=" + path,
                })
            } else {
                console.log(data.message);
                wx.showModal({
                    content: data.message,
                    confirmText: "确定",
                    cancelText: "取消",
                });
            }
        })
    },

    /************* 用户数据相关 **************/

    // 解密phoneNumber
    aesPhoneNumber: function (iv, encryptedData, path = "") {
        return new Promise((resolve, reject) => {
            user.aesPhoneNumber(iv, encryptedData, path).then(data => {
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    //请求当前用户是否有在扫码未关闭的信息
    remainseconds: function () {

        console.log(`#app.js remainseconds`)
        var that = this;
        if (!wx.getStorageSync('isLogin')) {
            return
        }
        user.remindLockStatus().catch(error => {
            that.setLoginChange(wx.getStorageSync("isLogin"))
        })
    },

    /************* 活动相关 ************/

    // 裂变活动获取hdUserId

    getHduserid: function (callback) {
        var that = this;
        let data = {
            mobile: wx.getStorageSync("userPhone"),
            usertoken: wx.getStorageSync("usertoken"),
            userid: wx.getStorageSync("userid")
        }
        let url = config.getHduserid
        $.post(url, data).then(data => {
            console.log("getHduserid()", data)
            if (data.code == 0) {
                wx.setStorageSync("hdUserId", data.detail.hdUserId);
                if (callback)
                    return callback(data.detail.hdUserId);
            } else {
                console.log("err:", data.message);
            }
        })
    },

    // 发起活动邀请
    start_invite: function () {
        var that = this;
        if (!wx.getStorageSync("isLogin")) {
            $.goto(config.page.login + '?path=activity')
            return
        }

        var data = {
            type: "1",
            usertoken: wx.getStorageSync("usertoken"),
            userid: wx.getStorageSync("userid"),
            appid: that.appId
        };
        let url = $.getUrl(config.isActivity, data)

        $.get(url).then(data => {
            if (data.detail.activity != null) {
                wx.setStorageSync("activityId", data.detail.activity[0].activityId);
                $.goto(config.page.getMonthCard)
            }
        })
    },

    //保存抢月卡助力信息
    saveAttendorInfo: function () {
        var that = this;
        that.saveAttendor()
    },
    //保存助力信息接口
    saveAttendor: function () {
        let data = {
            initorId: wx.getStorageSync('initorId'),
            score: wx.getStorageSync('hitCount'),
            usertoken: wx.getStorageSync("usertoken"),
            userid: wx.getStorageSync("userid"),
            mobile: wx.getStorageSync("userPhone")
        }
        let url = config.saveAttendorInfo
        $.post(url, data)
            .then(data => {
                console.log("saveAttendor", data)
                if (data.code != 0) {
                    // console.log("saveAttendor",data)
                } else {
                    if (!wx.getStorageSync('isLogin')) {
                        $.goto(config.page.login + '?path=attendorInfo', true)
                    } else {
                        wx.reLaunch({
                            url: config.page.invitorShareResult + '?hdCardInitiatorId=' + wx.getStorageSync("initorId"),
                        })
                    }

                }
            })
            .catch(error => {
                console.log(error)
            })
    }
})